package ArithMathOperation;
//*************************************************************************************
//    Judge.java        Author:方艺雯
//
//    对后缀的式子进行运算，产生正确的结果。
//*************************************************************************************
import java.util.*;

public class Judge
{
    Stack<String> calculate;

    public Judge()
    {
        calculate = new Stack<>();
    }

    public String answer(String stringwyh)
    {
        String Stringwyh = stringwyh.substring(0,stringwyh.length() - 2);
        //以空格为分隔符分开每个分数和运算符
        StringTokenizer NUM = new StringTokenizer(Stringwyh, " ");

        while (NUM.hasMoreTokens())
        {
            String xx = NUM.nextToken();//xx表示一个分数或字符

            if (xx.equals("+"))
            {
                String a = calculate.pop();
                String b = calculate.pop();

                String re = becom(a).add(becom(b)).toString();

                calculate.push(re);
            }//如果是运算符则进行计算
            else if (xx.equals("-"))
            {
                String a = calculate.pop();
                String b = calculate.pop();

                String re = becom(b).subtract(becom(a)).toString();

                calculate.push(re);
            }//如果是运算符则进行计算
            else if (xx.equals("*"))
            {
                String a = calculate.pop();
                String b = calculate.pop();

                String re = becom(a).multiply(becom(b)).toString();

                calculate.push(re);
            }//如果是运算符则进行计算
            else if (xx.equals("÷"))
            {
                String a = calculate.pop();
                String b = calculate.pop();

                String re = becom(b).divide(becom(a)).toString();

                calculate.push(re);
            }//如果是运算符则进行计算
            else
                calculate.push(xx);//如果是将分数则存入calculate栈中
            }
        return calculate.pop();
    }
    //把整数转为分数，把原有的分数转为分子的分数和分母的分数
    private RationalNumber becom(String str)
    {
        StringTokenizer tokenizer = new StringTokenizer(str, "/");
        int zi = Integer.parseInt(tokenizer.nextToken());
        int mu;
        if (tokenizer.hasMoreTokens())
            mu = Integer.parseInt(tokenizer.nextToken());
        else
            mu = 1;

        return new RationalNumber(zi, mu);
    }
}